"""empty message

Revision ID: caa4cab82b41
Revises: 1d3c1e2061f6
Create Date: 2025-04-28 18:26:24.305675

"""

import enum
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm

DeclarativeBase = orm.declarative_base()


class Visibility(enum.Enum):
    PRIVATE = 0
    LINK = 1
    PUBLIC = 2


class Recipe(DeclarativeBase):
    __tablename__ = "recipe"

    id = sa.Column(sa.Integer, primary_key=True)
    visibility: orm.Mapped[Visibility] = sa.Column(sa.Enum(Visibility))
    public: orm.Mapped[bool] = sa.Column(sa.Boolean)


# revision identifiers, used by Alembic.
revision = "caa4cab82b41"
down_revision = "1d3c1e2061f6"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    session = orm.Session(bind=bind)

    visibility_enum = sa.Enum("PRIVATE", "LINK", "PUBLIC", name="recipe_visibility")
    visibility_enum.create(op.get_bind(), checkfirst=True)

    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("recipe", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "visibility",
                visibility_enum,
                nullable=True,
            )
        )

    # Data migrations
    recipes = session.query(Recipe).all()
    for recipe in recipes:
        recipe.visibility = Visibility.LINK if recipe.public else Visibility.PRIVATE

    try:
        session.bulk_save_objects(recipes)
        session.commit()
    except Exception as e:
        session.rollback()
        raise e


    with op.batch_alter_table("recipe", schema=None) as batch_op:
        batch_op.alter_column('visibility', nullable=False)
        batch_op.drop_column("public")

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("recipe", schema=None) as batch_op:
        batch_op.add_column(sa.Column("public", sa.BOOLEAN(), nullable=False))
        batch_op.drop_column("visibility")

    # ### end Alembic commands ###
